import { createHttpRequest } from '@fssc/admin';
import Cookie from 'js-cookie';
import { RequestConfig } from '@fssc/share';
import type { InternalAxiosRequestConfig } from 'axios'
import { TOKEN_KEY } from '../util/const';

export const prefix = {
  passportAuth: '/passport'
}

type ConvertRequestConfig<Type> = {
  [Property in keyof Type]+?: Type[Property];
};

// 初始化请求配置
export type HttpRequestConfig = ConvertRequestConfig<RequestConfig> & {
  prefix?: Record<string, string>,
  source?: string,
  requestBefore?: (config: InternalAxiosRequestConfig) => void
}

const httpRequest = createHttpRequest(
  {
    baseURL: '',
    timeout: 60 * 1000,
    successCodes: [1, 200, '1000_0001_0000', 'SYS.SUCCESS'],
    onlyData: true
  }
);

// 初始化请求，改变默认请求配置
export function initRequest(config?: HttpRequestConfig) {
  httpRequest.setDefaultConfig(config || {});
  httpRequest.requestUse({
    onFulfilled(request) {
      request.headers.token = Cookie.get(TOKEN_KEY);
      request.headers.Source = request.headers.Source || config.source || 'fssc';

      if (config?.beforeRequest) {
        config.beforeRequest(request);
      }

      return request;
    },
  });

  if (config?.prefix) {
    Object.assign(prefix, config.prefix);
  }
}

export default httpRequest;
